package top.zimang.loveforwords.Activity;

import androidx.appcompat.app.AppCompatActivity;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;


import top.zimang.loveforwords.Base.BaseActivity;
import top.zimang.loveforwords.Model.Word;
import top.zimang.loveforwords.R;
import top.zimang.loveforwords.Service.SearchForWords;
import top.zimang.loveforwords.Utils.WordUtils;

public class SearchWordsActivity extends BaseActivity {
    String keyw;
    EditText editText;

    BroadcastReceiver wordReady;

    SearchForWords searchForWords;
    boolean mBound = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_words);
        Button ser4now=(Button) findViewById(R.id.SearchForNow);
        ser4now.setOnClickListener(this::onClick);
        editText=(EditText)findViewById(R.id.textFiled);


        Intent searchService =new Intent(this, SearchForWords.class);
        bindService(searchService,connection, Context.BIND_AUTO_CREATE);

        IntentFilter filter=new IntentFilter();
        filter.addAction("wordReady");
        wordReady=new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Intent it=new Intent(getContext(),DisplayWordActivity.class);
                it.putExtra("w",searchForWords.getWord());
                startActivity(it);
            }
        };
        registerReceiver(wordReady,filter);
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()){
            case R.id.SearchForNow:
                keyw=editText.getText().toString().trim();
                searchForWords.sendRequestWithOkHttp(keyw);
                break;
            default:
                break;
        }
    }

    /** Defines callbacks for service binding, passed to bindService() */
    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName className,
                                       IBinder service) {
            // We've bound to LocalService, cast the IBinder and get LocalService instance
            SearchForWords.SBinder binder = (SearchForWords.SBinder) service;
            searchForWords = binder.getService();
            mBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            mBound = false;
        }
    };

}